import { createApp, h, ref } from "vue";
import Dialog from "./index.vue";

interface DialogOptions {
  message: string; // 消息内容
  target: any; // 挂载目标
  title?: string; // 对话框标题
  closeable?: boolean; // 是否显示关闭按钮
  cancelText?: string; // 取消按钮文本
  confirmText?: string; // 确认按钮文本
  onCancel?: () => void; // 取消回调
  onConfirm?: () => void; // 确认回调
}

let dialogApp: ReturnType<typeof createApp> | null = null;

const show = ref(false); // 控制对话框显示状态
const currentOptions = ref<DialogOptions>({
  message: "", // 默认选项
  target: null
});

/**
 * 创建并显示对话框
 * @param options - 对话框选项
 */
const showDialog = (options: DialogOptions) => {
  if (!dialogApp) {
    dialogApp = createApp({
      setup() {
        const { title, closeable, cancelText, confirmText, ...rest } = options;
        return () =>
          h(
            Dialog,
            {
              show: show.value,
              title,
              closeable,
              cancelText,
              confirmText,
              ...rest,
              onCancel: () => handleClose(options.onCancel),
              onConfirm: () => handleClose(options.onConfirm),
              onClose: () => handleClose()
            },
            {
              default: () => (typeof options.message === "function" ? options.message() : options.message)

              // default: () => options.message
            }
          );
      }
    });

    const target = options.target?.$el || options.target;
    dialogApp.mount(target);
  }

  // 更新当前选项并显示对话框
  currentOptions.value = { ...options };
  show.value = true;
};

/**
 * 关闭对话框并执行回调
 * @param callback - 可选的回调函数
 */
const handleClose = (callback?: () => void) => {
  show.value = false;
  callback?.();
};

/**
 * 卸载对话框组件
 */
const destroyDialog = () => {
  if (dialogApp) {
    dialogApp.unmount();
    dialogApp = null;
    show.value = false;
    currentOptions.value = { message: "", target: null }; // 重置状态
  }
};

export { showDialog, destroyDialog, Dialog };
